package rss.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;

public class MyWordpress {

	private String xmlRpcUrl = "http://noigiovani.it/xmlrpc.php";
	private XMLRPCClient client;
	private int blog_id=1;
	private String username, password;

	public MyWordpress() {
		username="utenteRSS";
		password="passwordrss";
		creaClient();
	}

	public MyWordpress(String username, String password) {
		this.username=username;
		this.password=password;
		creaClient();
	}

	public void creaClient()
	{
		client = new XMLRPCClient(xmlRpcUrl, username, password);	
	}

	public ArrayList<Integer> generaArrayPostID (int numLastPost) throws XMLRPCException
	{
		ArrayList<Integer> arrayPostID=new ArrayList<Integer>();

		HashMap<String, Object> filtroGetLastPost=new HashMap<String, Object>();
		filtroGetLastPost.put("number", numLastPost); //imposto il numero degli ultimi post da ottenere
		filtroGetLastPost.put("post_status", "publish"); //imposto che lo stato dei post da prendere in considerazione deve essere pubblicato

		Object[] parametri = new Object[] {blog_id, username, password, filtroGetLastPost};
		Object[] posts;

		posts = (Object[])client.call("wp.getPosts", parametri);

		HashMap<String, Object> p = new HashMap<String,Object>();

		for(Object post: posts)
		{
			p = (HashMap<String, Object>) post;
			arrayPostID.add(Integer.parseInt((String)p.get("post_id")));
		}	
		return arrayPostID;
	}

	public int inserisciCommento(int postID, String content) throws XMLRPCException
	{
		HashMap<String, Object> commento=new HashMap<String, Object>();
		commento.put("content", content);
		Object[] parametri = new Object[] {blog_id, username, password, postID, commento};
		return (Integer) client.call("wp.newComment", parametri);
	}

	public ArrayList<Commento> getArrayCommenti(int postID) throws XMLRPCException
	{
		HashMap<String, Object> filtroGetComments=new HashMap<String,Object>();
		filtroGetComments.put("post_id", postID);
		filtroGetComments.put("status", "approve");
		Object[] paramsGetComments=new Object[]{blog_id, username, password, filtroGetComments};
		Object[] resultsGetComments=(Object[])client.call("wp.getComments", paramsGetComments);
		HashMap<String, Object> c=new HashMap<String,Object>();
		ArrayList<Commento> commenti=new ArrayList<Commento>(); 
		for(Object commentResult: resultsGetComments)
		{
			c=(HashMap<String, Object>)commentResult;
			String autore=(String)c.get("author");
			Date data=(Date)c.get("date_created_gmt");
			String contenuto=(String)c.get("content");
			commenti.add(new Commento(autore, data, contenuto));
		}
		return commenti;
	}
	
}
